package com.nova.bluetooth.xunFeiSDK.utils;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.nova.bluetooth.helpUtils.LogUtil;


/**
 * 返回流式识别的完整结果
 */
public class StreamingAsrUtil {
    //存储asr中间结果
    private static StringBuilder iatText = new StringBuilder();
    //存储asr最终结果
    private static String asrResult = "";

    /**
     * 解析听写结果更新当前语音消息的听写内容,返回当前完整结果
     */
    public static String processIATResult(JSONObject text) throws JSONException {
        Log.d("processIATResult", text.toString());
        JSONArray words = text.getJSONArray("ws");
        //第一句话(sn==1),清除上一句话的asr结果
        if (text.getInteger("sn") == 1) {
            asrResult = "";
        }

        for (int i = 0; i < words.size(); i++) {
            JSONArray charWord = words.getJSONObject(i).getJSONArray("cw");
            for (int j = 0; j < charWord.size(); j++) {
                iatText.append(charWord.getJSONObject(j).getString("w"));
//                LogUtil.d("test=======>"  + iatText.toString());
            }
        }

        boolean ls = text.getBoolean("ls");
        //中间结果长度≥最终结果，替换最终结果
        if (iatText.toString().length() >= asrResult.length() && !ls) {
            asrResult = iatText.toString();
        }

        if (ls){
            if (iatText.toString().length()> asrResult.length()){
                asrResult = iatText.toString();
            }else {
                asrResult = asrResult + iatText.toString();
            }
        }

        //清除中间结果，方便下次存储
        iatText.delete(0, iatText.length());

        return removeConsecutivePunctuation(asrResult);
    }



    /**
     * 去除相邻的多个标点符号，只保留一个。
     *
     * @param input 输入的字符串
     * @return 处理后的字符串
     */
    public static String removeConsecutivePunctuation(String input) {
        // 使用正则表达式匹配相邻的多个标点符号（包括中文和英文）
        String pattern = "([！？。，；：、!?.;:,]+)(\\1)+";
        // 替换为单个标点符号
        return input.replaceAll(pattern, "$1");
    }


    // 把转写结果解析为句子
    public static String getContent(String message) {
        LogUtil.d("test====>" + message);
        try {
            JSONObject messageObj = JSON.parseObject(message);
            JSONObject cn = messageObj.getJSONObject("cn");
            JSONObject st = cn.getJSONObject("st");
            boolean ls = messageObj.getBoolean("ls");
            JSONArray rtArr = st.getJSONArray("rt");
            String bg = st.getString("bg");//句子在整段语音中的开始时间，单位毫秒(ms),中间结果的bg为准确值

            if (ls){
                asrResult = "";
            }

            for (int i = 0; i < rtArr.size(); i++) {
                JSONObject rtArrObj = rtArr.getJSONObject(i);
                JSONArray wsArr = rtArrObj.getJSONArray("ws");
                for (int j = 0; j < wsArr.size(); j++) {
                    JSONObject wsArrObj = wsArr.getJSONObject(j);
                    JSONArray cwArr = wsArrObj.getJSONArray("cw");
                    for (int k = 0; k < cwArr.size(); k++) {
                        JSONObject cwArrObj = cwArr.getJSONObject(k);
                        String wStr = cwArrObj.getString("w");
                        String rl = cwArrObj.getString("rl"); //分离的角色编号
                        iatText.append(wStr);
                    }
                }
            }

            //中间结果长度≥最终结果，替换最终结果
            if (iatText.toString().length() >= asrResult.length()) {
                asrResult = iatText.toString();
            }

            if (ls){
                asrResult = asrResult + iatText.toString();
            }

            //清除中间结果，方便下次存储
            iatText.delete(0, iatText.length());

        } catch (Exception e) {
            return "Json解析出错了:" + message;
        }
        return asrResult;
    }

}

